package com.dawn.module.hospital.service;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dawn.framework.common.exception.ServerException;
import com.dawn.framework.common.pojo.CommonResult;
import com.dawn.framework.common.util.http.HttpUtils;
import com.dawn.framework.common.util.json.JsonUtils;
import com.dawn.module.cms.api.department.CmsDepartmentApi;
import com.dawn.module.cms.api.department.dto.CmsDepartmentRespDTO;
import com.dawn.module.cms.api.doctor.CmsDoctorApi;
import com.dawn.module.cms.api.doctor.dto.CmsDoctorRespDTO;
import com.dawn.module.hospital.controller.admin.statics.vo.SearchReqVO;
import com.dawn.module.hospital.controller.app.base.vo.ReqVO;
import com.dawn.module.hospital.controller.app.register.vo.*;
import com.dawn.module.hospital.enums.BHConstants;
import com.dawn.module.hospital.enums.ErrorCodeConstants;
import com.dawn.module.hospital.util.ChineseCharToEnUtils;
import com.dawn.module.hospital.util.DateUtils;
import com.dawn.module.hospital.util.RandomUtils;
import com.dawn.module.hospital.util.SecEncryptUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: cnsu-cmh
 * @time: 2024/8/7 15:49
 */
@Slf4j
@Service
public class RegisterService extends BHService {

    @Autowired
    private PatientService patientService;

    @Autowired
    private RefundService refundService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private TemplateMsgService templateMsgService;

    @Autowired
    private EhealthService ehealthService;

    @Autowired
    private EInvoiceService eInvoiceService;

    @Autowired
    private CmsDoctorApi cmsDoctorApi;

    @Autowired
    private CmsDepartmentApi cmsDepartmentApi;

    public CommonResult dateList(ReqVO reqVO) {
        List<Map> dateList = new ArrayList<>();
        String nowDateStr = DateUtils.formatDate(new Date(),"yyyy-MM-dd");
        String nowShowWeek = DateUtils.getWeekDay(new Date(),"星期");
        Map map = new HashMap<>();
        map.put("showDate","当日");
        map.put("dateStr",nowDateStr);
        map.put("showWeek",nowShowWeek);
        dateList.add(map);
        for(int i=1; i<6; i++){
            Date date =  DateUtils.getAddDay(new Date(),i);
            String dateStr = DateUtils.formatDate(date,"yyyy-MM-dd");
            Date day = DateUtils.parseDate(dateStr);
            String showDate = DateUtils.formatDate(day, "MM-dd");
            String showWeek = DateUtils.getWeekDay(day,"星期");
            map = new HashMap<>();
            map.put("showDate",showDate);
            map.put("dateStr",dateStr);
            map.put("showWeek",showWeek);
            dateList.add(map);
        }
        return CommonResult.success(dateList);

    }

    public CommonResult deptList(RegisterDeptQueryReqVO reqVO) {
        Map params = new HashMap();
        params.put("hisProvider", BHConstants.HIS_PROVIDER);
        params.put("tradeSerialNumber", RandomUtil.randomNumbers(9));
        params.put("userId",reqVO.getPatientId());
        params.put("dayNum",7);
        CommonResult result = HttpUtils.getHttp(getHisServerUri() + BHConstants.HIS_GET_REG_DEPT.getValue(), params);

        if (result.isError()){
            return result;
        }

        List<CmsDepartmentRespDTO> cmsdeptList = cmsDepartmentApi.getList();

        Map<String,List<Map>> deptMap = new HashMap<>();
        List<Map> mapList = (List<Map>) result.getData();
        for (Map dept : mapList) {
            String firstSpell = String.valueOf(ChineseCharToEnUtils.getFirstSpell(String.valueOf(dept.get("departmentName"))).toUpperCase().charAt(0));
            List<Map> hisDepartments;
            if(deptMap.containsKey(firstSpell)) {
                hisDepartments = deptMap.get(firstSpell);
            } else {
                hisDepartments = new ArrayList<>();
            }

            String departmentName = String.valueOf(dept.get("departmentName"));
            if(departmentName != null){
                List<CmsDepartmentRespDTO> cmsDoctor = cmsdeptList.stream().filter(m -> departmentName.equals(m.getName())).collect(Collectors.toList());
                if(cmsDoctor.size()>0){
                    dept.put("cms",cmsDoctor.get(0));
                }
            }

            hisDepartments.add(dept);
            deptMap.put(firstSpell,hisDepartments);
        }
        List<Map> deptList = new ArrayList<>();
        Map map = new HashMap();
        for (Map.Entry<String, List<Map>> entry : deptMap.entrySet()) {
            map = new HashMap();
            map.put("key",entry.getKey());
            map.put("data",entry.getValue());
            deptList.add(map);
        }
        deptList.sort(Comparator.comparing((Map m) -> String.valueOf(m.get("key"))));
        return CommonResult.success(deptList);
    }

    public CommonResult doctorList(RegisterDoctorQueryReqVO reqVO) {
        Map params = new HashMap();
        params.put("hisProvider", BHConstants.HIS_PROVIDER);
        params.put("partnerConpany",BHConstants.COMPANY_NAME);
        params.put("tradeSerialNumber", RandomUtil.randomNumbers(9));
        params.put("departmentId",reqVO.getDepartmentId());
        params.put("searchDate",reqVO.getSearchDate());
        CommonResult result = HttpUtils.getHttp(getHisServerUri() + BHConstants.HIS_GET_REG_DOCTOR.getValue(), params);

        if(result.isSuccess()) {
            JSONArray jsonArray = (JSONArray)result.getData();
            JSONArray array = jsonArray.getJSONObject(0).getJSONArray("doctors");
            List doctorList = array.stream().collect(Collectors.toList());

            List<CmsDoctorRespDTO> cmsDoctorList = cmsDoctorApi.getList();

            List doctors = new ArrayList();
            doctorList.sort(Comparator.comparing(d -> ((JSONObject)d).getString("scheduleTime")));
            doctorList.forEach(d -> {
                String cost = ((JSONObject) d).getString("cost");
                cost = new BigDecimal(cost).toString();
                ((JSONObject)d).put("cost",cost);

                String doctorName = ((JSONObject)d).getString("doctorName");
                if(doctorName != null){
                    List<CmsDoctorRespDTO> cmsDoctor = cmsDoctorList.stream().filter(m -> doctorName.equals(m.getName())).collect(Collectors.toList());
                    if(cmsDoctor.size()>0){
                        ((JSONObject)d).put("cms",cmsDoctor.get(0));
                    }
                }

                // 获取挂号费用明细
                Map queryMap = new HashMap();
                queryMap.put("hisProvider",BHConstants.HIS_PROVIDER);
                queryMap.put("patientId", reqVO.getPatientId());
                queryMap.put("number", ((JSONObject) d).getString("number"));
                queryMap.put("regTime", reqVO.getSearchDate());
                queryMap.put("idCardNo", reqVO.getIdCardNo());
                queryMap.put("name", reqVO.getPatientName());
                queryMap.put("bookingMethod", "0");
                queryMap.put("projectId", ((JSONObject) d).getString("projectId"));
                CommonResult resultQuery = HttpUtils.getHttp(getHisServerUri() + BHConstants.HIS_GET_REG_FEE.getValue(), queryMap);
                log.info("-------register 获取挂号费用明细-----resultQuery:"+JsonUtils.toJsonString(resultQuery));
                if(resultQuery.isSuccess()) {
                    JSONObject mapData = (JSONObject) resultQuery.getData();
                    List<Map> mapResList = (List<Map>) mapData.get("XMMX");
                    ((JSONObject)d).put("zje",mapData.get("ZJE"));
                    if(mapResList!=null && mapResList.size()>0){
                        ((JSONObject)d).put("feeList",mapResList.get(0).get("XM"));
                    }
                }

                Integer dayparting = ((JSONObject) d).getInteger("dayparting");
                if(dayparting == 1){
                    List<Map> span = (List<Map>) ((JSONObject) d).get("doctorSpan");
                     if(span!=null && span.size()>0) {
                         ((JSONObject)d).put("hasSources",1);
                     } else {
                         ((JSONObject)d).put("hasSources",0);
                     }
                    doctors.add(d);
                } else {
                    Integer limitCount = ((JSONObject) d).getInteger("limitCount");
                    if (limitCount != null && limitCount > 0) {
                        ((JSONObject)d).put("hasSources",1);
                    } else {
                        ((JSONObject)d).put("hasSources",0);
                    }
                    doctors.add(d);
                }
            });
            return CommonResult.success(doctors);
        }
        return result;
    }

    public CommonResult createOrder(RegisterCreateReqVO reqVO) {
        //保存挂号信息
        Map params = new HashMap();
        params.put("pid",reqVO.getPId());
        params.put("registerNo", reqVO.getOrderNumber());
        params.put("userId", reqVO.getUserId());
        params.put("patientId", reqVO.getPatientId());
        params.put("patientName", reqVO.getPatientName());
        params.put("cardNo", reqVO.getCardNo());
        params.put("clinicNo", reqVO.getClinicNo());
        params.put("regDate", reqVO.getRegDate());
        params.put("regTypeId", reqVO.getRegTypeId());
        params.put("regType", reqVO.getRegType());
        params.put("departmentId", reqVO.getDepartmentId());
        params.put("departmentName", reqVO.getDepartmentName());
        params.put("doctorId", reqVO.getDoctorId());
        params.put("doctorName", reqVO.getDoctorName());
        params.put("totalCost", reqVO.getTotalCost());
        params.put("amount", reqVO.getTotalCost());
        params.put("number", reqVO.getNumber());
        params.put("clinicId", reqVO.getClinicId());
        params.put("scheduleId", reqVO.getScheduleId());
        params.put("scheduleName", reqVO.getScheduleName());

        params.put("sequence", 0);
        params.put("scheduleTime", reqVO.getScheduleTime());
        params.put("scheduleTimeStar", reqVO.getScheduleTimeStar());
        params.put("address", reqVO.getAddress());


        if (BHConstants.ALIPAY_MINI_APPLET.getCode().equals(reqVO.getAppType())) {
            // 支付宝小程序
            if("chs".equals(reqVO.getPayType())) {
                params.put("payTypeID", BHConstants.PAY_CARD_ALI_CHS_CODE);
                params.put("payModeName", BHConstants.PAY_CARD_ALI_CHS_HIS);
            } else {
                params.put("payTypeID", BHConstants.PAY_CARD_ALI_CODE);
                params.put("payModeName", BHConstants.PAY_CARD_ALI_HIS);
            }
            params.put("payPlatform", BHConstants.PAY_PLATFORM_TYPE_ALI);
            params.put("payScene", BHConstants.ALIPAY_MINI_APPLET.getMsg());
        } else if(BHConstants.WEIXIN_SERVICE_ACCOUNTS.getCode().equals(reqVO.getAppType())){
            // 微信公众号
            if("chs".equals(reqVO.getPayType())) {
                // TODO 待HIS给出数据后修改
                params.put("payTypeID", BHConstants.PAY_CARD_WX_CHS_CODE);
                params.put("payModeName", BHConstants.PAY_CARD_WX_CHS_HIS);
            } else {
                params.put("payTypeID", BHConstants.PAY_CARD_WX_CODE);
                params.put("payModeName", BHConstants.PAY_CARD_WX_HIS);
            }

            params.put("payPlatform", BHConstants.PAY_PLATFORM_TYPE_WX_NAME);
            params.put("payScene", BHConstants.WEIXIN_SERVICE_ACCOUNTS.getMsg());
        }
        CommonResult result = HttpUtils.getHttp(getHisServerUri() + BHConstants.HIS_ADD_REG_ORDER.getValue(), params);
        return result;
    }

    public CommonResult sourceCheck(RegisterSourceCheckReqVO reqVO) {
        String key = reqVO.getDepartmentId()+"_"+reqVO.getDoctorId()+"_"+reqVO.getScheduleTime();
        String value = stringRedisTemplate.opsForValue().get(key);
        if(!StringUtils.hasLength(value)){
            stringRedisTemplate.opsForValue().set(key, reqVO.getPatientId(), 3, TimeUnit.MINUTES);
            return CommonResult.success("可挂号源");
        }

        if (value.equals(reqVO.getPatientId())){
            stringRedisTemplate.opsForValue().set(key, reqVO.getPatientId(), 3, TimeUnit.MINUTES);
            return CommonResult.success("可挂号源");
        }

        return CommonResult.error(ErrorCodeConstants.BH_ERROR.getCode(),reqVO.getScheduleTime() + "时段号源已被占用，请选择其他时段");
    }

    public CommonResult unLockRegNumber(RegisterUnLockReqVO reqVO) {
        String beginDate = LocalDateTimeUtil.format(reqVO.getBeginTime(),"yyyy-MM-dd HH:mm:ss");
        String endDate = LocalDateTimeUtil.format(reqVO.getEndTime(),"yyyy-MM-dd HH:mm:ss");
        log.warn("------- UnlockNumberTask 解锁号源 ----- begin ");
        Map params = new HashMap();
        log.warn("------- UnlockNumberTask 获取解锁号源获取数据 ----- beginTime:"+beginDate+",endTime:"+endDate);
        params.put("status", "unpaid");
        params.put("beginDate", beginDate);
        params.put("endDate",endDate);
        CommonResult result = HttpUtils.getHttp(getHisServerUri() + BHConstants.HIS_GET_UNPAID.getValue(), params);
        log.warn("-------UnlockNumberTask result-----result:" + JsonUtils.toJsonString(result));
        if(result.isSuccess()){
            JSONArray array = (JSONArray) result.getData();
            if(CollectionUtils.isNotEmpty(array)) {
                for (Object o : array) {
                    JSONObject jsonObject = (JSONObject) o;

                    if("unpaid".equals(jsonObject.getString("payStatus")) && !"0".equals(jsonObject.getString("sequence"))){
//                        Date d1 = DateUtils.getBeforeDate(new Date(),-2);
//                        Date d2 = DateUtils.getBeforeDate(new Date(),-1);
//                        if(DateUtils.belongCalendar(register.getCreateTime(),d1,d2)){
                        log.warn("-------UnlockNumberTask 解锁号源请求数据-----register:" + JsonUtils.toJsonString(jsonObject));
//                        Map unlockMap = new HashMap();
//                        unlockMap.put("hisProvider", BHConstants.HIS_PROVIDER);
//                        unlockMap.put("tradeSerialNumber",RandomUtil.randomNumbers(9));
//                        unlockMap.put("partnerCompany",BHConstants.COMPANY_NAME);
//                        unlockMap.put("orderNumber",jsonObject.getString("registerNo"));
//                        CommonResult unlockResult = HttpUtils.getHttp(getHisServerUri() + BHConstants.HIS_UN_LOCK_REG_NUMBER.getValue(), unlockMap);
                        CommonResult unlockResult = unLockRegNum(jsonObject.getString("registerNo"));
//                        if (unlockResult.isError()) {
//                            log.warn("------- UnlockNumberTask 解锁号源失败 -----message:"+unlockResult.getMsg());
//                        }else {
//                            log.warn("------- UnlockNumberTask 解锁号源成功 -----message:"+unlockResult.getMsg());
//                        }
//                        }

                    }
                }
            }
        }

        log.warn("------- UnlockNumberTask 解锁号源 ----- end ");
        return result;
    }

    public CommonResult unLockRegNum(String orderNumber) {
        Map unlockMap = new HashMap();
        unlockMap.put("hisProvider", BHConstants.HIS_PROVIDER);
        unlockMap.put("tradeSerialNumber",RandomUtil.randomNumbers(9));
        unlockMap.put("partnerCompany",BHConstants.COMPANY_NAME);
        unlockMap.put("orderNumber",orderNumber);
        CommonResult unlockResult = HttpUtils.getHttp(getHisServerUri() + BHConstants.HIS_UN_LOCK_REG_NUMBER.getValue(), unlockMap);
        if (unlockResult.isError()) {
            log.warn("------- UnlockNumberTask 解锁号源失败 -----message:"+unlockResult.getMsg());
        }else {
            log.warn("------- UnlockNumberTask 解锁号源成功 -----message:"+unlockResult.getMsg());
        }
        return unlockResult;
    }

    public CommonResult lockRegNumber(String orderNumber) {
        Map params = new HashMap();
        params.put("hisProvider", BHConstants.HIS_PROVIDER);
        params.put("tradeSerialNumber",RandomUtil.randomNumbers(9));
        params.put("partnerCompany",BHConstants.COMPANY_NAME);
        params.put("orderNumber",orderNumber);
        CommonResult result = HttpUtils.getHttp(getHisServerUri() + BHConstants.HIS_LOCK_REG_NUMBER.getValue(), params);
        return result;
    }

    public CommonResult register(RegisterCreateReqVO reqVO) {
        String orderNumber = "GH" + RandomUtils.buildRandomStr(4);
        reqVO.setOrderNumber(orderNumber);

        CommonResult addRegResult = createOrder(reqVO);
        if(addRegResult.isError()) {
            return addRegResult;
        }

        JSONObject orderDetails = new JSONObject();
        orderDetails.put("patientName", reqVO.getPatientName());
        orderDetails.put("patientId", reqVO.getPatientId());
        orderDetails.put("cardNo", reqVO.getCardNo());
        orderDetails.put("clinicNo", reqVO.getClinicNo());
        orderDetails.put("userId", reqVO.getUserId());
        orderDetails.put("openid", reqVO.getOpenid());
        orderDetails.put("pid", reqVO.getPId());

        CommonResult lockRegResult = lockRegNumber(orderNumber);
        if(lockRegResult.isError()) {
            return lockRegResult;
        }

        BigDecimal totalCost = new BigDecimal(reqVO.getTotalCost());
        int intValue = totalCost.multiply(new BigDecimal(100)).intValue();

        HashMap<String,Object> map = new HashMap();
        map.put("totalCost", totalCost);
        map.put("orderNumber", orderNumber);

        if(intValue > 0){

        }
        orderDetails.put("billMap",reqVO);
        orderDetails.put("orderNumber",orderNumber);
        orderDetails.put("totalCost",totalCost);
        orderDetails.put("orderName",reqVO.getOrderName());
        stringRedisTemplate.opsForValue().set("OrderDetails_"+orderNumber,orderDetails.toJSONString(),30L, TimeUnit.MINUTES);
        return CommonResult.success(reqVO);
    }

    public CommonResult buildPaySignData(String orderNumber) {
        Object orderObj = stringRedisTemplate.opsForValue().get("OrderDetails_" + orderNumber);
        if(orderObj == null) {
            return CommonResult.error(ErrorCodeConstants.BH_ERROR.getCode(), "订单数据不存在或已失效");
        }
        String cacheOrderData = orderObj.toString();
        JSONObject prePayInfo = JSON.parseObject(cacheOrderData);

        Map<String,Object> map = new HashMap<>();
        map.putAll(prePayInfo);
        JSONObject signDataJson = new JSONObject();
        signDataJson.put("patientId",prePayInfo.getString("patientId"));
        signDataJson.put("patientName",prePayInfo.getString("patientName"));
        signDataJson.put("clinicNo",prePayInfo.getString("clinicNo"));
        signDataJson.put("cardNo",prePayInfo.getString("cardNo"));
        signDataJson.put("pid",prePayInfo.getString("pid"));
        signDataJson.put("userId",prePayInfo.getString("userId"));
        signDataJson.put("openid",prePayInfo.getString("openid"));
        signDataJson.put("registerNo",prePayInfo.getString("registerNo"));
        signDataJson.put("orderName",prePayInfo.getString("orderName"));
        signDataJson.put("totalCost",prePayInfo.getString("totalCost"));
        signDataJson.put("orderNumber",orderNumber);

        String signData = null;
        try {
            signData = SecEncryptUtil.encryption(signDataJson.toJSONString());
        } catch (Exception e) {
            throw new ServerException(ERROR_CODE,e.getMessage());
        }
        map.put("signDataStr", signData);
        return CommonResult.success(map);
    }

    public CommonResult queryByOrderNumber(String orderNumber) {
        Map params = new HashMap();
        params.put("orderNumber",orderNumber);
        CommonResult result = HttpUtils.getHttp(getHisServerUri() + BHConstants.HIS_GET_REG_ORDER.getValue(), params);
        return result;
    }

    public CommonResult localRecord(SearchReqVO reqVO) {
        Map params = new HashMap();
        params.put("userId", reqVO.getUserId());
        params.put("patientId", reqVO.getPatientId());
        params.put("beginDate",reqVO.getBeginDate());
        params.put("endDate",reqVO.getEndDate());
        CommonResult result = HttpUtils.getHttp(getHisServerUri() + BHConstants.HIS_GET_REG_RECORD_LOCAL.getValue(), params);
        return result;
    }

    public CommonResult registerCancel(String orderNumber) {
        CommonResult findResult = queryByOrderNumber(orderNumber);
        if(!findResult.isSuccess()) {
            return findResult;
        }
        JSONObject orderObj = (JSONObject)findResult.getData();
        String patientId = orderObj.getString("patientId");
        String patientName = orderObj.getString("patientName");
        String totalCost = orderObj.getString("totalCost");
        String payScene = orderObj.getString("payScene");


        Map params = new HashMap();
        params.put("hisProvider", BHConstants.HIS_PROVIDER);
        params.put("orderNumber",orderNumber);
        params.put("preType",BHConstants.PAY_CARD_WX_HIS);
        CommonResult cancelResult = HttpUtils.getHttp(getHisServerUri() + BHConstants.HIS_REG_CANCEL.getValue(), params);
        if(cancelResult.isError()){
            return cancelResult;
        }

        unLockRegNum(orderNumber);

        CommonResult refundResult = refundService.refundSys(BHConstants.ORDER_TYPE_REG,BHConstants.WEIXIN_SERVICE_ACCOUNTS.getMsg() + "退号",orderObj);

        if(refundResult.isError()){
            cancelResult = CommonResult.error(ErrorCodeConstants.BH_ERROR.getCode(),"退号成功、退费失败,请联系管理员");
        }

        templateMsgService.sendMsgRegisterCancel(orderObj);
        return cancelResult;
    }

    public CommonResult payNotify(Map params){
        log.info("---------挂号缴费成功通知-------params:"+ JSONUtil.toJsonStr(params));

        Long pId = Long.valueOf(params.get("patientId").toString());
        String orderNumber = String.valueOf(params.get("orderNumber")) ;
        String thirdOrderNo = String.valueOf(params.get("thirdOrderNo")) ;
        String openid = String.valueOf(params.get("openid")) ;
        String totalCost = String.valueOf(params.get("totalCost")) ;
        String payInfo = String.valueOf(params.get("payInfo")) ;

        CommonResult patientResult = patientService.findPatientById(pId);
        JSONObject patient = (JSONObject)patientResult.getData();

        CommonResult findResult = queryByOrderNumber(orderNumber);
        if(!findResult.isSuccess()) {
            return findResult;
        }
        JSONObject orderObj = (JSONObject)findResult.getData();
        if(StringUtils.hasLength(orderObj.getString("procedureStatus"))) {
            String procedureStatus = orderObj.getString("procedureStatus");
            if("success".equals(procedureStatus)) {
                return CommonResult.success("操作成功");
            }
            if("fails".equals(procedureStatus)) {
                return CommonResult.success("操作成功");
            }
        }
        String payScene = orderObj.getString("payScene");

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hisProvider", BHConstants.HIS_PROVIDER);
        paramMap.put("partnerCompany",BHConstants.COMPANY_NAME);
        paramMap.put("bookingMethod",BHConstants.COMPANY_NAME);
        paramMap.put("tradeSerialNumber", RandomUtil.randomNumbers(9));
        paramMap.put("orderNumber",orderNumber);//挂号单号
        paramMap.put("thirdOrderNo",thirdOrderNo);
        paramMap.put("payInfo", JsonUtils.toJsonString(payInfo));

        if(BHConstants.ALIPAY_MINI_APPLET.getMsg().equals(payScene)) {
            paramMap.put("payWay", BHConstants.PAY_CARD_ALI_CODE);
        } else {
            paramMap.put("payWay", BHConstants.PAY_CARD_WX_CODE);
        }

        CommonResult payResult = HttpUtils.postForm(getHisServerUri() + BHConstants.HIS_PAY_REG_ORDER.getValue(), paramMap);
        if (payResult.isSuccess()) {

            JSONObject resultData = (JSONObject)payResult.getData();

            // 微信公众号
            if(BHConstants.WEIXIN_SERVICE_ACCOUNTS.getMsg().equals(payScene)) {
                // TODO 推送微信模板信息
                templateMsgService.sendMsgRegister(orderObj);
                // TODO 上传数据到电子健康卡
                // 上传数据到电子健康卡
                if(StringUtils.hasLength(getEhealthCfg().getHospitalId())) {
                    try{
                        String ehealthCardId = patient.getString("ehealthCardId");
                        if(StringUtils.hasLength(ehealthCardId)) {
                            String idCard = patient.getString("cardNo");
                            String scene;
                            if(DateUtils.getTimeYYMMDD().equals(orderObj.getString("regDate"))) {
                                //当日挂号
                                scene = "0101012";
                            } else {
                                //预约挂号
                                scene = "0101011";
                            }
                            ehealthService.uploadData(ehealthCardId,idCard,scene,orderObj.getString("departmentName"));

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                // 开据电子票据
                try{
                    CommonResult eReceiptResult = eInvoiceService.open(BHConstants.ORDER_TYPE_REG,resultData);
                    log.warn(orderNumber + "开据电子票据" + orderNumber + JsonUtils.toJsonString(eReceiptResult));
                } catch (Exception e) {
                    e.printStackTrace();
                    log.warn("电子票据开据失败 " + orderNumber);
                }

            }
            // 支付宝小程序
            if(BHConstants.ALIPAY_MINI_APPLET.equals(payScene)) {

            }
        } else {
            // 支付数据回写HIS失败
            // 推送退费审核模板消息
            refundService.saveRefundExamine(BHConstants.ORDER_TYPE_REG,orderObj,payResult.getMsg());

            return CommonResult.success(payResult.getMsg());
        }
        return CommonResult.success("");
    }

    public CommonResult seeRecord(RegisterQueryReqVO reqVO) {
        Map params = new HashMap();
        params.put("hisProvider", BHConstants.HIS_PROVIDER);
        params.put("tradeSerialNumber",RandomUtil.randomNumbers(9));
        params.put("partnerCompany",BHConstants.COMPANY_NAME);
        params.put("payTypeID",BHConstants.COMPANY_NAME);
        params.put("patientId", reqVO.getPatientId());
        params.put("jls","10");//记录数
        params.put("idCrdNo",reqVO.getCardNo());
        params.put("name",reqVO.getPatientName());
        CommonResult result = HttpUtils.getHttp(getHisServerUri() + BHConstants.HIS_GET_SEE_RECORD.getValue(), params);
        return result;
    }

    public CommonResult waitSee(RegisterQueryReqVO reqVO) {
        Map params = new HashMap();
//        sourceCode=868546&sourceType=门诊
        params.put("sourceCode",reqVO.getPatientId());
        params.put("sourceType","门诊");
        String result = HttpUtils.getHttpStr(getCallServerUri() + BHConstants.HIS_CALL_WAIT_SEE.getValue(), params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.getInteger("status") == 200){
            JSONArray jsonArray = jsonObject.getJSONArray("data");
            return CommonResult.success(jsonArray);
        }
        return CommonResult.error(ERROR_CODE,jsonObject.getString("msg"));
    }

    public CommonResult signIn(RegisterQueryReqVO reqVO) {
        Map params = new HashMap();
        //排队候诊ID
        params.put("patientId",reqVO.getRegisterNo());
        String result = HttpUtils.getHttpStr(getCallServerUri() + BHConstants.HIS_CALL_SIGN_IN.getValue(), params);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if(jsonObject.getInteger("status") == 200){
            JSONObject object = jsonObject.getJSONObject("data");
            return CommonResult.success(object);
        }
        return CommonResult.error(ERROR_CODE,jsonObject.getString("msg"));
    }
}
